package com.demo.task;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.demo.datasource.DataSourceContextHolder;
import com.demo.entity.BaseFile;
import com.demo.service.BaseFileService;
import com.demo.util.FTPUtils;
import com.demo.util.pro;
import com.feilong.core.date.DateUtil;

@Component  
@PropertySource("classpath:properties/task.properties")
public class MyTask {  
	
	@Resource 
	private BaseFileService fileService;
	
	/***
	 * 获取未上传的列表
	 * @return
	 */
	public List<BaseFile> unUploadFileList() {
		List<BaseFile> baseFiles = fileService.selectUnUploadFileList();
		return baseFiles;
	}
	
	
	
    @Scheduled(cron="${jobs.schedule}") //间隔
    public void taskCycle(){  
        System.out.println("定时器执行");

        String out = "";
		List<BaseFile> baseFiles = unUploadFileList();
		String pathU=pro.getUrlPath();
		String path = "";
		String num =Integer.toString(DateUtil.getDayOfMonth(new Date()) % 10);
		FTPUtils myFtp = new FTPUtils();
	    try
	    {
	    	
	    	myFtp.connect(pro.getFtpId(),pro.getFtpPort(), pro.getFtpUser(), pro.getFtpPwd()); 
			for (int i = 0; i < baseFiles.size(); i++) {
				BaseFile baseFile = baseFiles.get(i);
				String newFileName = changeName(baseFile.getPoliceId(),baseFile.getStartCaptureTime(),1,baseFile.getName());
				String newThumbnailName = changeName(baseFile.getPoliceId(),baseFile.getStartCaptureTime(),2,baseFile.getName());
				String importTime =DateUtil.toString(baseFile.getImportTime(), "yyyy-MM-dd"); 
				String writePath = "disk"+num+"/"+baseFile.getWorkstationSid()+"/Media/"+baseFile.getPoliceId()+"/"+importTime+"/";
				path = pathU +"disk"+num+"/"+baseFile.getWorkstationSid()+"/Media/"+baseFile.getPoliceId()+"/"+importTime+"/";
				System.out.println(path+"    "+newFileName+"   "+newThumbnailName);
				//文件夹创建
				File file = new File(path);
				if (!file.exists() && !file.isDirectory()) {
					System.out.println("文件夹不存在,创建");
					file.setWritable(true,false);
					file.mkdirs();
				}
				//文件传输   5为传输成功
				String fileDownloadPath = getTypeOfPath(0, baseFile.getPath());
				int fileDownload = myFtp.download(fileDownloadPath, path+newFileName).getStatus();
				//缩略图传输  5位传输成功
				String thumbnailDownloadPath = getTypeOfPath(1, baseFile.getThumbnail());
				int thumbnailDownload = myFtp.download(thumbnailDownloadPath, path+newThumbnailName).getStatus();
				//缩略图
				baseFile.setThumbnail(writePath+newThumbnailName);
				//文件路径
				baseFile.setPath(writePath+newFileName);
				//文件名
				baseFile.setName(newFileName);
				//下载文件&&缩略图&&保存数据库   更新第一个数据库索引
				DataSourceContextHolder.setDbType("two");
				int insertOut = fileService.insert(baseFile);
				
				if (fileDownload == 5 && thumbnailDownload==5 && insertOut > 0 ) {
					System.out.println("下载文件和缩略图成功");
					baseFile.setFileUpload(1);
					DataSourceContextHolder.setDbType("one");
					if (fileService.updateUploadFile(baseFile.getSid()) > 0) {
						//删除FTP
						Integer abc =myFtp.delete(fileDownloadPath).getStatus();
						//删除缩略图
						if (baseFile.getType() !=2) {
							Integer bcd = myFtp.delete(thumbnailDownloadPath).getStatus();
							System.out.println(bcd+"     缩略图："+thumbnailDownloadPath);
						}
						System.out.println(abc+"     文件："+fileDownloadPath);
						
					};
				}
			}
			myFtp.disconnect(); 
	    }catch(IOException e) {
	    	System.out.println("FTP上传文件异常：" + e.getMessage());
	    }
		System.out.println(out);
    }
    
    
    /***
	 *@param thumbnail 0文件   1缩略图
	 *@param path 路径
	 * @return String
	 */
	public String getTypeOfPath(Integer thumbnail,String path){
		String out="";
		if (thumbnail == 1) {
			//out = "/Thumbnail/mp3.jpg";
			path = path.replace("\\", "/");
			out = path.substring(path.indexOf("/")+1);
			out = out.substring(out.indexOf("/")+1);
			out = "/"+out;
		}else{
			out = "/"+path;
		}
		return out;
	}
	
	
	/***
	 * 名称定义
	 * @param policeId
	 * @param startCaptureTime
	 * @param thumbnail
	 * @param name
	 * @return
	 */
	private String changeName(String policeId, Date startCaptureTime,Integer thumbnail, String name) {
		String out="";
		out = policeId+"@";
		out += DateUtil.toString(startCaptureTime, "yyyy-MM-dd_HH-mm-ss");
		String[] names = name.split("[.]");
		if (thumbnail.equals(1)) {
			out += "."+names[1];
		}else{
			out += "_thumbnail.jpg";
		}
		return out;
	}
    
    
    
}  